<?php
declare (strict_types = 1);

namespace app\api\traits;

use app\api\service\ApiResponse;
use app\api\service\StatusCode;
use app\api\validate\ParamMustBePostiveInt;
use think\exception\ValidateException;

trait Curd
{
    /**
     * @NodeAnotation(title="列表")
     */    
    public function index()
    {
		//sleep(15);
        list($page, $limit, $where) = $this->buildTableParames();
        $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
        return ApiResponse::success($list);
    }

    /**
     * 单条读取
     * @MethodAuthor: 聂哥
     * @Date: 2023-03-03 00:37:09
     */
    public function read($id)
    {
        $id = (new ParamMustBePostiveInt())->paramCheck();
        $list = $this->model->where('id',$id)->find();
        return ApiResponse::success($list);
    }

    /**
     * 创建
     * @MethodAuthor: 聂哥
     * @Date: 2023-03-03 00:36:52
     */
    public function save()
    {
        $post = $this->request->post();
        $validate = new $this->validate();
        if ($validate->check($post) == false) 
            throw new ValidateException($validate->getError());
        
        $result = $this->model::create($post);
        if( !$result ){
            return json(['statusCode'=>200,'statusMsg'=>'保存失败']);
        }
        return ApiResponse::create(StatusCode::CREATED,null,['id'=>$result->id]);
    }

    /**
     * 删除
     * @MethodAuthor: 聂哥
     * @Date: 2023-03-03 00:36:31
     */
    public function delete()
    {
        $id = (new ParamMustBePostiveInt())->paramCheck();
        $row = $this->model->where('id',$id)->find();
        if( !$row ){
            throw new ValidateException('无效的id');
        }
        $row->delete();
        return ApiResponse::create(StatusCode::SUCCESS,'删除成功');
    }

    /**
     * 更新
     * @MethodAuthor: 聂哥
     * @Date: 2023-03-03 00:36:05
     */
    public function update($id)
    {
        $post = $this->request->post(); 
        $validate = new $this->validate();
        if ($validate->check($post) == false) 
            return json(['statusCode'=>400,'statusMsg'=>$validate->getError()]);
        
        $id = $this->request->param('id');
        $where['id']= $id;
        $result = $this->model::update($post,$where);
        if( !$result ){
            return json(['statusCode'=>200,'statusMsg'=>'保存失败']);
        }
        return json(['statusCode'=>200,'statusMsg'=>'保存成功']);
    }
}